import java.security.KeyPairGenerator;
import java.util.Map;

class RSAKit {
	public static void main(String[] args) {

	}

	/**
	 * 1,生成公钥与私钥
	 */
	public static void createKeys(int keySize){
		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");//为RSA算法创建一个keyPairGenerator对象
		kpg.initialize(keySize);//初始化KeyPairGenerator对象,密钥长度
		KeyPair keyPair = kpg.generateKeyPair();//生成密钥对
		Key publicKey = keyPair.getPublic();//得到公钥
        Key privateKey = keyPair.getPrivate();//得到私钥
        String publicKeyStr = new BASE64Encoder().encode(publicKey.getEncoded());//将字节数组转换成base64编码的字符串
        String privateKeyStr = new BASE64Encoder().encode(privateKey.getEncoded());//将字节数组转换成base64编码的字符串
    
        System.out.printf("publicKey", publicKeyStr);
        System.out.printf("privateKey", privateKeyStr);
	}

	/**
     * 2,获取公钥
     * @param publicKeyStr
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     */
    public static RSAPublicKey getPublicKey(String publicKeyStr) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(new BASE64Decoder().decodeBuffer(publicKeyStr));  //通过X509编码的Key指令获得公钥对象
        RSAPublicKey publicKey = (RSAPublicKey) keyFactory.generatePublic(x509EncodedKeySpec);
        return publicKey;
    }

    /**
     * 3,获取私钥
     * @param privateKeyStr
     * @return
     * @throws NoSuchAlgorithmException
     * @throws IOException
     * @throws InvalidKeySpecException
     */
    public static RSAPrivateKey getPrivateKey(String privateKeyStr) throws NoSuchAlgorithmException, IOException, InvalidKeySpecException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr));//通过PKCS#8编码的Key指令获得私钥对象
        RSAPrivateKey privateKey = (RSAPrivateKey) keyFactory.generatePrivate(pkcs8EncodedKeySpec);
        return privateKey;
    }

	 /**
     * 4,公钥加密
     * @param content
     * @param publicKey
     * @return
     * @throws NoSuchPaddingException
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     * @throws BadPaddingException
     * @throws IllegalBlockSizeException
     */
    public static byte[] publicEncrypt(byte[] content, PublicKey publicKey) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE,publicKey);
        byte[] bytes = cipher.doFinal(content);
        return bytes;
	}
	

}




